<!-- 房间信息 -->
<template>
	<!-- :data="optionsData" -->
	<vxe-grid ref="grid" v-bind="gridOptions" class="grid">
		<template #toolbar>
			<vxe-toolbar class="toolbar">
				<template #buttons>
					<a-space>
						<a-input-group compact class="display-flex">
							<a-form-item-rest>
								<a-select v-model:value="roomData.houseType" :options="itemOptions" style="width: 100px" @change="change" />
							</a-form-item-rest>
							<a-select
								v-model:value="roomData.communityIdList"
								:options="options.community"
								mode="multiple"
								max-tag-count="responsive"
								:field-names="{label: 'name', value: 'id'}"
								option-filter-prop="name"
								show-search
								allow-clear
								placeholder="请选择项目/小区"
								@change="handler"
								style="width: 200px"></a-select>
						</a-input-group>
						<a-input-group compact class="display-flex">
							<a-form-item-rest>
								<a-select v-model:value="roomData.matchType" :options="relationshipList" style="width: 100px" />
							</a-form-item-rest>
							<a-input
								style="width: 200px"
								v-model:value="roomData.like"
								allow-clear
								@keydown.enter="handler"
								placeholder="房间号/房源地址" />
						</a-input-group>
						<a-select
							v-model:value="roomData.isCheckIn"
							:options="statusList"
							allow-clear
							placeholder="入住状态"
							@change="handler"
							style="width: 100px" />
						<a-button type="primary" @click="handler">
							<search-outlined />
						</a-button>
					</a-space>
				</template>
				<template #tools>
					<a-space :size="20" v-if="visibles.editable">
						<a-button @click.stop="openBatchCheckIn(false)" :loading="loadings.submit">取消</a-button>
						<a-button type="primary" @click.stop="submit" :loading="loadings.submit">保存</a-button>
					</a-space>
					<!-- 企业合同已退租无效不展示批量入住按钮 -->
					<a-button
						type="primary"
						v-if="!visibles.editable && ![31, 32,33, 34,41,42].includes(props.contractLabel as number)"
						@click.stop="openBatchCheckIn(true)">
						批量入住
					</a-button>
				</template>
			</vxe-toolbar>
		</template>
		<template #build="{row}">
			<div>{{ row.address }}</div>
		</template>
		<template #actualPrice="{row}">
			<div>{{ row.actualPrice.toLocaleString() }}</div>
		</template>
		<template #deposit="{row}">
			<div>
				{{ row.deposit }}
				<span v-show="row.deposit">.00</span>
			</div>
		</template>

		<template #houseArea="{row}">
			<div>
				{{ row.houseArea }}
				<span v-if="row.houseArea">平</span>
			</div>
		</template>
		<template #userLimit="{row}">
			<span>{{ formatCheckInNum(row.userlimit).userlimit }}</span>
			/
			<span
				v-if="![31, 32, 33, 34, 41, 42].includes(row.label)"
				v-color="{color: formatCheckInNum(row.userlimit, row.checkInNum).color}">
				{{ formatCheckInNum(null, row.checkInNum).checkInNum }}
			</span>
			<span v-else>-</span>
		</template>
		<template #isCheckIn="{row}">
			<!-- 31-正常退 32-违约退 33-协议退 34-未结算 41-已作废 42-已拒绝 -->
			<div v-if="![31, 32, 33, 34, 41, 42].includes(row.label)" class="status-box">
				<div :class="[row.isCheckIn === 1 ? 'is-check-in' : 'check-in']"></div>
				<div>{{ row.isCheckIn === 1 ? '未入住' : '已入住' }}</div>
			</div>
			<div v-else>-</div>
		</template>
		<template #checkInStaff="{row}">
			<!-- 非审批中的才展示 -->
			<a-popover
				v-if="![1, 2, 4].includes(row.approvalStatus) && ![31, 32, 33, 34, 41, 42].includes(row.label)"
				overlayClassName="get-popover-ele"
				trigger="click"
				@visible-change="
					val => {
						setStaffList(val, row)
					}
				">
				<template #title></template>
				<template #content>
					<a-transfer
						:data-source="filterStaffList"
						show-search
						:selectedKeys="selectedKeysList"
						:filter-option="filterOption"
						:target-keys="row.selection"
						:render="item => item.title"
						:listStyle="{
							minHeight: '350px',
							minWidth: '200px'
						}"
						@selectChange="
							(keys, tarKeys) => {
								selectChange(keys, tarKeys, row)
							}
						"
						@change="
							val => {
								handleChange(val, row)
							}
						" />
				</template>
				<a-input v-model:value="row.enterEmployeeValue" inputReadOnly placeholder="请选择入住员工" />
			</a-popover>
		</template>
		<template #checkInDate="{row}">
			<a-date-picker
				v-if="![1, 2, 4].includes(row.approvalStatus) && ![31, 32, 33, 34, 41, 42].includes(row.label)"
				:format="DATE_FORMAT.DATE"
				:disabledDate="disabledDate"
				v-model:value="row.checkInStartDateTime" />
		</template>
		<!-- <template #action="{row}"> -->
		<!-- <a v-if="row.isCheckIn === 1 && row.houseStatus === 30 && hasPermissions(['mk_contract_enterprise_staff_blrz'])" @click="checkIn(row)">入住</a> -->
		<!-- <a v-if="row.isCheckIn !== 1 && row.houseStatus === 30 && hasPermissions(['mk_contract_enterprise_staff_bl'])" @click="removeHouseShow(row.enterPriseEmployeeId, row)">搬离</a> -->
		<!-- </template> -->
	</vxe-grid>
	<!-- 个人入住 -->
	<staff-check-in v-model:visible="record.batchCheckIn" :type="3" :id="record.id" :info="staffInfo" @close="getList(1)" />
	<!-- 搬离 -->
	<!-- <remove-house v-model:visible="record.removeHouseShow" :id="record.id" @success="getList(1)" /> -->
	<move-out-dialog v-model:visible="record.removeHouseShow" :id="record.id" @success="getList(1)" />
	<!-- 通行授权弹窗 -->
	<access-authorization-rewrite-dialog :houseInfoArr="houseInfoArr" v-model:visible="visibles.accessAuth" @success="onCancel" />
</template>

<script setup lang="ts">
	import {onMounted, reactive, ref} from 'vue'
	import {VxeGridProps} from 'vxe-table'
	import {SearchOutlined} from '@ant-design/icons-vue'
	import houseApi from '@/api/house-api'
	import {batchCheckInHouse, employeeList} from '@/api/staff-pool'
	import {pagerConfig, proxyConfigProps} from 'yuxin-base/src/utils/vxe-table'
	import {getRoomListPaging} from '@/api/charter-contract'
	import StaffCheckIn from '@/components/contract/enterprise-customer-management/staff-check-in.vue'
	import {message, Modal} from 'ant-design-vue'
	import {useStore} from '@/store'
	import moveOutDialog from '@/components/contract/contract-detail-dialog/charter-contract/move-out.vue'
	import dayjs from 'dayjs'
	import {getBatchDeviceAuth} from '@/api/device'
	import DATE_FORMAT from 'yuxin-base/src/utils/date'
	import XEUtils from 'xe-utils'
	import {enterEmployInfo} from '@/interface/roomInfo'
	import AccessAuthorizationRewriteDialog from '@/components/contract/add-tenant-contract-dialog/access-authorization-rewrite-dialog.vue'
	// import RemoveHouse from '@/components/contract/enterprise-customer-management/remove-house.vue'

	const hasPermissions = useStore().hasPermissions
	const props = defineProps<{
		id: string
		staffInfo: {id: string}
		approvalStatus?: string
		processInstanceId?: string
		status: any
		// 企业合同状态
		contractLabel: string | number | null
	}>()
	let modalInstance: any = null
	const selectedKeysList = ref([])
	const staffList = ref<Array<enterEmployInfo>>([]) // 所有企业员工
	const checkedStaffList = ref<Array<string>>([]) // 已经选中的所有集合
	const filterStaffList = ref<Array<enterEmployInfo>>([]) // 左侧列表
	/**
	 * @params
	 * userlimit 限制人数 checkInNum 入住人数
	 */
	const formatCheckInNum = (userlimit?: number | null, checkInNum?: number | null) => {
		const _u = userlimit || 0
		const _c = checkInNum || 0
		const _userlimit = userlimit ? (userlimit < 10 ? '0' + userlimit : userlimit) : '-'
		const _checkInNum = checkInNum ? (checkInNum < 10 ? '0' + checkInNum : checkInNum) : '-'
		const _color = !userlimit || _c > _u ? 'danger' : ''

		return {
			userlimit: _userlimit,
			checkInNum: _checkInNum,
			color: _color
		}
	}
	const grid = ref()
	const visibles = reactive({
		accessAuth: false,
		editable: false
	})
	// 是否开启批量入住
	const battchCheckInStatus = ref(false)
	const relationshipList = reactive([
		{
			label: '全部',
			value: null
		},
		{
			label: '房间号',
			value: 1
		},
		{
			label: '房源地址',
			value: 3
		}
	])

	const itemOptions = reactive([
		{
			label: '项目名称',
			value: 3
		},
		{
			label: '小区名称',
			value: 1
		}
	])

	const options = reactive({
		community: []
	})

	const statusList = ref([
		{
			label: '未入住',
			value: 1
		},
		{
			label: '已入住',
			value: 2
		}
	])
	const roomData = reactive<any>({
		enterPriseContractId: null,
		matchType: null,
		like: null,
		current: 1,
		size: 15,
		houseType: 3,
		communityIdList: [],
		isCheckIn: null
	})

	const gridOptions = reactive<VxeGridProps>({
		height: 'auto',
		showOverflow: true,
		rowConfig: {
			isHover: true
		},
		columns: [
			{
				width: 200,
				fixed: 'left',
				title: '项目名称/小区名称',
				field: 'communityName'
			},
			{
				title: '楼栋信息/房间号',
				minWidth: 350,
				slots: {
					default: 'build'
				}
			},
			{
				title: '租金(元)',
				minWidth: 100,
				slots: {
					default: 'actualPrice'
				}
			},
			{
				title: '押金(元)',
				minWidth: 100,
				slots: {
					default: 'deposit'
				}
			},
			{
				title: '面积',
				minWidth: 100,
				slots: {
					default: 'houseArea'
				}
			},
			{
				title: '设定可住人数/实际入住人数',
				minWidth: 200,
				slots: {
					default: 'userLimit'
				}
			},
			{
				title: '状态',
				width: 150,
				slots: {
					default: 'isCheckIn'
				}
			},
			{
				title: '入住员工',
				width: 200,
				fixed: 'right',
				align: 'center',
				field: 'checkInStaff',
				slots: {
					default: 'checkInStaff'
				},
				visible: false
			},
			{
				title: '入住日期',
				width: 200,
				fixed: 'right',
				align: 'center',
				field: 'checkInDate',
				slots: {
					default: 'checkInDate'
				},
				visible: false
			}
		],
		pagerConfig,
		proxyConfig: {
			props: proxyConfigProps,
			ajax: {
				async query({page: {currentPage: current, pageSize: size}}) {
					roomData.enterPriseContractId = props.id
					const res = await getRoomListPaging({...roomData, current, size})
					if (res.data?.records)
						res.data.records.forEach(i => {
							i.selection = []
							i.enterEmployeeValue = ''
						})
					return res
				}
			}
		}
	})
	const getList = (page?: any) => {
		grid.value?.commitProxy(page === 1 ? 'reload' : 'query')
	}
	const handler = () => {
		roomData.enterPriseContractId = props.id
		getList(1)
	}
	const staffCheckInInfo = ref<any>({})
	const record = reactive({
		batchCheckIn: false,
		removeIn: false,
		removeHouseShow: false,
		id: '',
		houseId: ''
	})
	/**
	const checkIn = row => {
		// if (['1', 1].includes(props.approvalStatus as string)) return message.error('当前包租合同审批中，暂不允许入住。')
		if (['1', 1].includes(row.approvalStatus as number)) return message.error('当前合同审批中，暂不允许入住。')
		// if (['2'].includes(props.approvalStatus as string)) return message.error('当前包租合同审批驳回，暂不允许入住。')
		record.batchCheckIn = true
		record.id = props.staffInfo?.id || ''
		record.houseId = row.id
		staffCheckInInfo.value = props.staffInfo
		staffCheckInInfo.value.fullAddress = row.fullAddress
	}
	const removeHouseShow = (enterPriseEmployeeId, row) => {
		// if (['1', 1].includes(props.approvalStatus as string)) return message.error('当前包租合同审批中，暂不允许搬离。')
		if (['1', 1].includes(row.approvalStatus as number)) return message.error('当前合同审批中，暂不允许搬离。')
		// if (['2'].includes(props.approvalStatus as string)) return message.error('当前包租合同审批驳回，暂不允许搬离。')
		record.removeHouseShow = true
		record.id = enterPriseEmployeeId
	}
	 */
	// 获取员工列表
	const getEmployeeList = () => {
		let params = {
			enterPriseId: props.staffInfo?.id,
			current: 1,
			size: 999
		}
		employeeList(params).then(res => {
			const dataList = (res.data.records || []).map(i => {
				return {
					...i,
					disabled: 3 === i.status, //已入住的员工需要禁用(1 未入住 2 已搬离 3 已搬离)
					key: i.id,
					title: 3 === i.status ? i.employeeName + ' (已入住)' : i.employeeName + `(${i.phone})`
				}
			})
			staffList.value = dataList
			filterStaffList.value = XEUtils.clone(dataList)
		})
	}
	const loadings = reactive({
		calc: false,
		save: false,
		submit: false
	})
	const getHouseCommunityList = () => {
		const params = {type: roomData.houseType === 1 ? 1 : 2}

		houseApi
			.getHouseCommunityList(params)
			.then(({data = []}) => {
				options.community = data
			})
			.finally(() => (loadings.calc = false))
	}
	onMounted(() => {
		getHouseCommunityList()
		getEmployeeList()
	})

	const filterOption = (inputValue: string, option: any) => {
		return option.title.indexOf(inputValue) > -1
	}

	const handleChange = (keys: string[], row: any) => {
		const {fullData} = grid.value.getTableData()
		row.selection = keys
		checkedStaffList.value = fullData.reduce((prev, curr) => {
			return [...prev, ...curr.selection]
		}, [])
		row.enterEmployeeValue = staffList.value
			.filter(i => keys.includes(i.id))
			.map(i => i.employeeName)
			.join('，')
	}

	const selectChange = (keys: string[], targetKeys, row: any) => {
		// 往右移
		if (keys.length) {
			if (keys.length + (row.checkInNum || 0) > row.userlimit || 0) {
				// 不允许重复弹窗
				if (!modalInstance) {
					modalInstance = Modal.warning({
						title: '提示',
						content: '该房间实际入住数已高于设定入住数，请确认是否仍要办理入住。',
						getContainer: document.querySelector('.get-popover-ele') as HTMLDivElement,
						onOk() {
							modalInstance.destroy()
							modalInstance = null
						}
					})
				}
			}
			keys.forEach(i => row.selection.push(i))
			handleChange(row.selection, row)
			selectedKeysList.value = []
			return
		}
		// 往左移
		if (targetKeys.length) {
			row.selection = row.selection.filter(i => !targetKeys.includes(i))
			handleChange(row.selection, row)
			selectedKeysList.value = []
			return
		}
	}

	// 保存
	const submit = () => {
		const {fullData} = grid.value.getTableData()
		const charterContractFromList = fullData.reduce((prev, curr) => {
			const _s: Array<any> = []
			if (curr.selection.length) {
				curr.selection.forEach(i => {
					_s.push({
						deliveryType: 1,
						compactType: 2,
						communityName: curr.communityName,
						charterMoney: curr.actualPrice,
						houseAddress: curr.fullAddress,
						houseId: curr.id,
						houseType: curr.houseType,
						compactId: curr.contractId,
						enterPriseContractId: props.id,
						enterEmployeeId: i,
						checkInStartDateTime: curr.checkInStartTime
							? dayjs(curr.checkInStartTime).format(DATE_FORMAT.DATE)
							: dayjs(new Date()).format(DATE_FORMAT.DATE),
						checkInEndTime: dayjs(curr.endTime).format(DATE_FORMAT.DATE)
					})
				})
			}
			return [...prev, ..._s]
		}, [])
		if (0 === charterContractFromList.length) {
			message.error('请先选择入住员工')
			return
		}
		// 下发授权参数
		const AccessAuthParams = fullData.reduce((prev, curr) => {
			if (curr.selection.length) {
				return [
					...prev,
					{
						houseId: curr.id,
						compactId: curr.contractId,
						enterpriseEmployeeIds: curr.selection
					}
				]
			} else {
				return [...prev]
			}
		}, [])
		loadings.submit = true
		batchCheckInHouse({charterContractFromList})
			.then(res => {
				// 批量下发授权
				batchDeviceAccessAuth(AccessAuthParams)
			})
			.finally(() => {
				loadings.submit = false
			})
	}

	// 批量下发授权
	const houseInfoArr = ref([])
	const batchDeviceAccessAuth = (selectionArr: Array<any>) => {
		const params = selectionArr.map(i => {
			return {id: i.compactId, houseId: i.houseId, enterpriseEmployeeIds: i.enterpriseEmployeeIds}
		})
		getBatchDeviceAuth(params).then(({data}) => {
			data.forEach(i => {
				i.sourceType = 2
				;(i.renterInfos || []).forEach(j => {
					j.accessAuthType = []
					j.lockAuthType = []
				})
			})
			houseInfoArr.value = data || []
			if (!data.map(i => i.showAccessLock).includes(true)) {
				message.success('操作成功')
				onCancel()
			} else if (data.map(i => i.hasLock).includes(true) || data.map(i => i.hasAccess).includes(true)) {
				visibles.accessAuth = true
			} else {
				message.success('操作成功')
				onCancel()
			}
		})
	}

	const onCancel = () => {
		getList(1)
		getEmployeeList()
		openBatchCheckIn(false)
		houseInfoArr.value = []
		selectedKeysList.value = []
		checkedStaffList.value = []
	}

	// 只能选择今天之后
	const disabledDate = current => {
		return dayjs(current).isBefore(dayjs().subtract(1, 'day')) // 今天之前(包括今天)
	}

	// 每次打开弹窗之前需要过滤一遍数据避免重复入住
	const setStaffList = (vis, row) => {
		if (vis) {
			// 先把已经选中的需要排除出去
			const getCurrStaffList = checkedStaffList.value.filter(i => !row.selection.includes(i))
			filterStaffList.value = staffList.value.filter(i => !getCurrStaffList.includes(i.id))
		}
	}

	// 打开批量入住时显示对应列
	const openBatchCheckIn = (editable: boolean) => {
		visibles.editable = editable

		const columnFields = ['checkInStaff', 'checkInDate']

		columnFields.forEach(field => {
			grid.value[editable ? 'showColumn' : 'hideColumn'](field)
		})
	}

	const change = () => {
		roomData.enterPriseContractId = props.id
		getHouseCommunityList()

		getList(1)
	}
</script>

<style lang="less" scoped>
	.grid {
		.toolbar {
			width: 100%;

			.check-in-status {
				margin-bottom: 0px;
			}
		}

		.status-box {
			display: flex;
			align-items: center;

			.is-check-in {
				width: 6px;
				height: 6px;
				line-height: 27px;
				border-radius: 50%;
				background: #52c41a;
				margin-right: 8px;
				opacity: 1;
			}

			.check-in {
				width: 6px;
				height: 6px;
				line-height: 27px;
				border-radius: 50%;
				background: #0266ff;
				margin-right: 8px;
				opacity: 1;
			}
		}
	}
</style>

<style lang="less">
	.get-popover-ele {
		.ant-transfer-operation {
			& > button {
				display: none !important;
			}
		}
	}
</style>
